<template>
  <view class="publish-buddy-page">
    <!-- Header Section -->
    <header class="header">
      <image class="header-image" src="/static/header-bg.png" mode="aspectFill"></image>
      <view class="header-bar">
        <image class="back-btn" src="/static/back-icon.png" mode="aspectFit" @click="goBack"></image>
        <image class="page-title-image" src="/static/publish-buddy.png" mode="aspectFit"></image>
      </view>
    </header>

    <!-- Form Content -->
    <scroll-view scroll-y class="form-content">
      <view class="form-card">
        <!-- 搭子类型 -->
        <view class="form-item">
          <text class="form-label">搭子类型</text>
          <picker 
            :value="typeIndex"
            :range="buddyTypes"
            range-key="text"
            @change="onTypeChange"
          >
            <view class="form-value">
              <text :class="['form-value-text', !formData.typeId ? 'placeholder' : '']">
                {{ formData.typeName || '请选择搭子类型' }}
              </text>
              <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
            </view>
          </picker>
        </view>

        <!-- 单价 -->
        <view class="form-item">
          <text class="form-label">单价</text>
          <view class="form-value">
            <text class="form-value-text">{{ formData.price ? `¥${formData.price}` : '--' }}</text>
          </view>
        </view>

        <!-- 标题 -->
        <view class="form-item">
          <text class="form-label">标题</text>
          <view class="form-value">
            <input 
              class="form-input" 
              v-model="formData.title" 
              placeholder="请输入20字以内的标题"
              maxlength="20"
            />
          </view>
        </view>

        <!-- 详细内容 -->
        <view class="form-item form-item-full">
          <text class="form-label">详细内容</text>
          <textarea 
            class="form-textarea" 
            v-model="formData.content" 
            placeholder="请输入500字以内的内容"
            maxlength="500"
            auto-height
          ></textarea>
        </view>

        <!-- 图片上传 -->
        <view class="form-item form-item-full" style="margin-top: 0; padding-top: 0;">
          <view class="upload-card" @click="addImage" v-if="formData.images.length < 9">
            <image class="camera-icon" src="/static/up-photo.png" mode="aspectFit"></image>
            <text class="upload-text">点击上传</text>
          </view>
          <view v-if="formData.images.length > 0" class="gallery">
            <view 
              v-for="(img, index) in formData.images" 
              :key="index"
              class="gallery-item"
            >
              <image :src="img" class="gallery-image" mode="aspectFill"></image>
              <!-- H5 等平台 -->
              <view class="gallery-delete" @click.stop="removeImage(index)">
                <image class="delete-icon" src="/static/del.png" mode="aspectFit" />
              </view>
              <!-- 小程序平台覆盖层 -->
              <cover-view class="gallery-delete" @click.stop="removeImage(index)">
                <cover-image class="delete-icon" src="/static/del.png" />
              </cover-view>
            </view>
          </view>
          <text class="upload-tips">请上传4:3比例,大小2m以内jpg、png图片</text>
        </view>

        <!-- 性别限制 -->
        <view class="form-item">
          <text class="form-label">性别限制</text>
          <picker 
            :value="genderIndex"
            :range="genderOptions"
            range-key="label"
            @change="onGenderChange"
          >
            <view class="form-value">
              <text class="form-value-text">{{ genderText }}</text>
              <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
            </view>
          </picker>
        </view>

        <!-- 开始时间 -->
        <view class="form-item">
          <text class="form-label">开始时间</text>
          <view class="form-value">
            <picker 
              mode="multiSelector" 
              :value="timePickerIndex" 
              :range="timePickerRange"
              range-key="label"
              @change="onTimePickerChange"
              @columnchange="onTimePickerColumnChange"
            >
              <view class="form-value-inner">
                <text :class="['form-value-text', !formData.startTime ? 'placeholder' : '']">
                  {{ formatTime(formData.startTime) || '请选择' }}
                </text>
                <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
              </view>
            </picker>
          </view>
        </view>

        <!-- 时长 -->
        <view class="form-item">
          <text class="form-label">时长（小时）</text>
          <view class="form-value">
            <input 
              class="form-input" 
              type="number" 
              v-model="formData.duration" 
              placeholder="请输入时长"
            />
          </view>
        </view>

        <!-- 活动地点 -->
        <view class="form-item">
          <text class="form-label">活动地点</text>
          <view class="form-value" @click="selectLocation">
            <text :class="['form-value-text', !formData.location ? 'placeholder' : '']">
              {{ locationDisplayText }}
            </text>
            <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
          </view>
        </view>

        <!-- 参与人数 -->
        <view class="form-item">
          <text class="form-label">参与人数</text>
          <view class="form-value">
            <input 
              class="form-input" 
              type="number" 
              v-model="formData.participants" 
              placeholder="请输入人数"
              :min="1"
              @blur="validateParticipants"
            />
            <text class="form-unit">人</text>
          </view>
        </view>

        <!-- 指定用户参与 -->
        <view class="form-item">
          <text class="form-label">指定用户参与</text>
          <view class="form-value" @click="openDesignatedUsersModal">
            <text :class="['form-value-text', designatedUsersText === '请选择' ? 'placeholder' : '']">
              {{ designatedUsersText }}
            </text>
            <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
          </view>
        </view>

        <!-- 是否需要现场确认 -->
        <view class="form-item">
          <text class="form-label">是否需要现场确认</text>
          <picker 
            :value="needOnsiteConfirmIndex"
            :range="needOnsiteConfirmOptions"
            range-key="label"
            @change="onNeedOnsiteConfirmChange"
          >
            <view class="form-value">
              <text class="form-value-text">{{ needOnsiteConfirmText }}</text>
              <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
            </view>
          </picker>
        </view>
      </view>

      <!-- 支付方式白框 -->
      <view class="payment-card">
        <view class="payment-section">
          <radio-group @change="onPaymentChange">
            <label class="payment-item" v-for="item in paymentMethods" :key="item.value">
              <view
                class="pay-item"
                :class="{ 'selected': formData.paymentMethod === item.value }"
              >
                <view class="pay-item-left">
                  <view class="pay-icon-wrapper">
                    <image
                      class="pay-icon"
                      :src="item.icon"
                      mode="aspectFit"
                    />
                  </view>
                  <view class="pay-item-info">
                    <text class="pay-method-title">{{ getPaymentTitle(item) }}</text>
                    <text class="pay-method-desc">{{ item.desc }}</text>
                  </view>
                </view>
                <view class="pay-item-right">
                  <radio
                    :value="item.value"
                    color="#2977FF"
                    style="transform: scale(0.9)"
                    :checked="formData.paymentMethod === item.value"
                  />
                </view>
              </view>
            </label>
          </radio-group>
        </view>
      </view>
    </scroll-view>

    <!-- 发布按钮 -->
    <view class="publish-section">
      <button class="publish-btn" :disabled="!canPublish" @click="handlePublish">
        发布 (需支付 ¥{{ publishFee }})
      </button>
    </view>



    <!-- 指定用户选择弹框 -->
    <view v-if="showDesignatedUsersModal" class="designated-users-modal" @click="closeDesignatedUsersModal">
      <view class="designated-users-content" @click.stop>
        <view class="designated-users-header">
          <text class="designated-users-cancel" @click="closeDesignatedUsersModal">取消</text>
          <text class="designated-users-title">选择用户</text>
          <text class="designated-users-confirm" @click="confirmDesignatedUsers">确定</text>
        </view>
        <scroll-view scroll-y class="designated-users-list">
          <view v-if="followList.length === 0" class="empty-tip">
            <text>暂无关注</text>
          </view>
          <view v-else>
            <view 
              v-for="item in followList" 
              :key="item.id" 
              class="designated-user-item"
              @click="toggleUserSelect(item)"
            >
              <image class="designated-user-avatar" :src="item.avatar || '/static/default-avatar.png'" mode="aspectFill" />
              <view class="designated-user-info">
                <text class="designated-user-nickname">{{ item.nickname || item.username || '用户' }}</text>
                <text class="designated-user-id">ID {{ item.uid || item.id }}</text>
              </view>
              <view class="designated-user-checkbox">
                <view 
                  class="checkbox-icon" 
                  :class="{ 'checked': isUserSelected(item.id) }"
                >
                  <text v-if="isUserSelected(item.id)" class="checkbox-check">✓</text>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import BuddyApi from '@/sheep/api/member/buddy'
import FileApi from '@/sheep/api/infra/file'
import user from '@/sheep/store/user'
import UserApi from '@/sheep/api/member/user'
import PayOrderApi from '@/sheep/api/pay/order'

const userStore = user()

// 表单数据
const formData = ref({
  typeId: '',
  typeName: '',
  price: '',
  title: '',
  content: '',
  images: [],
  gender: 'all', // all, male, female
  startTime: '',
  duration: '',
  location: '',
  longitude: null, // 经度
  latitude: null, // 纬度
  participants: '1',
  designatedUsers: [], // 用户ID数组
  needOnsiteConfirm: true,
  paymentMethod: 'alipay' // wallet, alipay, wechat
})

// 搭子类型列表
const buddyTypes = ref([])
const typeIndex = ref(0)

// 性别选项
const genderOptions = [
  { label: '男女不限', value: 'all' },
  { label: '仅限男生', value: 'male' },
  { label: '仅限女生', value: 'female' }
]
const genderIndex = ref(0)

// 是否需要现场确认选项
const needOnsiteConfirmOptions = [
  { label: '是', value: true },
  { label: '否', value: false }
]
const needOnsiteConfirmIndex = ref(0)

// 指定用户选择弹框
const showDesignatedUsersModal = ref(false)
const followList = ref([]) // 关注的用户列表
const selectedUsers = ref([]) // 临时选中的用户ID数组

// 时间选择器
const currentYear = new Date().getFullYear()
const years = Array.from({ length: 20 }, (_, i) => currentYear - 5 + i)
const months = Array.from({ length: 12 }, (_, i) => i + 1)
const getDays = (year, month) => {
  const daysInMonth = new Date(year, month, 0).getDate()
  return Array.from({ length: daysInMonth }, (_, i) => i + 1)
}
const hours = Array.from({ length: 24 }, (_, i) => String(i).padStart(2, '0'))
const minutes = Array.from({ length: 60 }, (_, i) => String(i).padStart(2, '0'))

// 时间选择器范围
const timePickerRange = computed(() => {
  const yearList = years.map(y => ({ label: `${y}年`, value: y }))
  const monthList = months.map(m => ({ label: `${m}月`, value: m }))
  const dayList = getDays(selectedTime.value.year, selectedTime.value.month).map(d => ({ label: `${d}日`, value: d }))
  const hourList = hours.map(h => ({ label: `${h}时`, value: parseInt(h) }))
  const minuteList = minutes.map(m => ({ label: `${m}分`, value: parseInt(m) }))
  return [yearList, monthList, dayList, hourList, minuteList]
})

// 当前选择的时间
const selectedTime = ref({
  year: currentYear,
  month: new Date().getMonth() + 1,
  day: new Date().getDate(),
  hour: new Date().getHours(),
  minute: new Date().getMinutes()
})

// 时间选择器索引
const timePickerIndex = ref([0, 0, 0, 0, 0])


// 发布费用计算：单价*参与人数
const publishFee = computed(() => {
  const price = parseFloat(formData.value.price) || 0
  const participants = parseInt(formData.value.participants) || 0
  return price * participants
})

// 用户余额
const userBalance = ref(0)

// 支付方式列表
const paymentMethods = ref([
  {
    icon: '/static/balance-pay.png',
    title: '余额支付',
    desc: '会员钱包,方便取用',
    value: 'wallet',
  },
  {
    icon: '/static/wx-pay.png',
    title: '微信支付',
    desc: '亿万用户的选择,更快更安全',
    value: 'wechat',
  },
  {
    icon: '/static/ali-pay.png',
    title: '支付宝支付',
    desc: '支付宝安全支付',
    value: 'alipay',
  },
])

// 获取支付方式标题（带余额显示）
const getPaymentTitle = (item) => {
  if (item.value === 'wallet') {
    return `余额支付（¥${userBalance.value.toFixed(2)}）`
  }
  return item.title
}

// 支付方式选择
const onPaymentChange = (e) => {
  formData.value.paymentMethod = e.detail.value
}

// 验证参与人数
const validateParticipants = () => {
  const participants = parseInt(formData.value.participants) || 0
  if (participants < 1) {
    formData.value.participants = '1'
    uni.showToast({
      title: '参与人数至少为1',
      icon: 'none'
    })
  }
}

// 计算属性
const genderText = computed(() => {
  const option = genderOptions.find(opt => opt.value === formData.value.gender)
  return option ? option.label : '男女不限'
})

const needOnsiteConfirmText = computed(() => {
  return formData.value.needOnsiteConfirm ? '是' : '否'
})

// 指定用户参与显示文本
const designatedUsersText = computed(() => {
  if (formData.value.designatedUsers.length === 0) {
    return '请选择'
  }
  return `已选择${formData.value.designatedUsers.length}人`
})

// 活动地点显示文本（最多15个字）
const locationDisplayText = computed(() => {
  if (!formData.value.location) {
    return '请选择'
  }
  if (formData.value.location.length > 15) {
    return formData.value.location.substring(0, 15) + '...'
  }
  return formData.value.location
})

const canPublish = computed(() => {
  return formData.value.typeId && 
         formData.value.typeName &&
         formData.value.price &&
         formData.value.title && 
         formData.value.content &&
         formData.value.startTime &&
         formData.value.duration &&
         formData.value.participants &&
         formData.value.paymentMethod
  // 注意：location（活动地点）和 designatedUsers（指定用户参与）不是必填项
})

// 方法
const goBack = () => {
  uni.navigateBack()
}

// 获取搭子类型列表
const getBuddyTypeList = async () => {
  try {
    const res = await BuddyApi.getBuddyTypeList()
    if (res && res.code === 0 && res.data) {
      buddyTypes.value = res.data.map(item => ({
        value: item.id,
        text: item.typeName,
        amount: item.amount || 0
      }))
    }
  } catch (error) {
    console.error('获取搭子类型列表失败:', error)
    // 如果API失败，使用默认数据
    buddyTypes.value = [
      { value: 1, text: '游戏搭子', amount: 50 },
      { value: 2, text: '旅游搭子', amount: 100 },
      { value: 3, text: '饭搭子', amount: 80 },
      { value: 4, text: '运动搭子', amount: 60 }
    ]
  }
}

// 搭子类型选择
const onTypeChange = (e) => {
  const index = e.detail.value
  typeIndex.value = index
  const selected = buddyTypes.value[index]
  if (selected) {
    formData.value.typeId = selected.value
    formData.value.typeName = selected.text
    // 根据选择的搭子类型设置单价
    formData.value.price = selected.amount || ''
  }
}

// 性别选择
const onGenderChange = (e) => {
  const index = e.detail.value
  genderIndex.value = index
  formData.value.gender = genderOptions[index].value
}

// 是否需要现场确认选择
const onNeedOnsiteConfirmChange = (e) => {
  const index = e.detail.value
  needOnsiteConfirmIndex.value = index
  formData.value.needOnsiteConfirm = needOnsiteConfirmOptions[index].value
}

// 格式化时间显示
const formatTime = (timeValue) => {
  if (!timeValue) return ''
  try {
    // 支持时间戳（数字）或时间字符串
    const date = typeof timeValue === 'number' ? new Date(timeValue) : new Date(timeValue)
    if (isNaN(date.getTime())) return timeValue
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}`
  } catch (e) {
    return timeValue
  }
}

// 格式化开始时间为后端需要的格式 "YYYY-MM-DD HH:mm:ss"
const formatStartTime = (timeValue) => {
  if (!timeValue) return ''
  try {
    // 支持时间戳（数字）或时间字符串
    const date = typeof timeValue === 'number' ? new Date(timeValue) : new Date(timeValue)
    if (isNaN(date.getTime())) return ''
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    const second = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`
  } catch (e) {
    return ''
  }
}

// 初始化时间选择器
const initTimePicker = () => {
  let date
  if (formData.value.startTime) {
    // 支持时间戳（数字）或时间字符串
    date = typeof formData.value.startTime === 'number' 
      ? new Date(formData.value.startTime) 
      : new Date(formData.value.startTime)
  } else {
    date = new Date()
  }
  
  selectedTime.value = {
    year: date.getFullYear(),
    month: date.getMonth() + 1,
    day: date.getDate(),
    hour: date.getHours(),
    minute: date.getMinutes()
  }
  
  // 计算索引
  const yearIndex = years.indexOf(selectedTime.value.year)
  const monthIndex = selectedTime.value.month - 1
  const currentDays = getDays(selectedTime.value.year, selectedTime.value.month)
  const dayIndex = Math.min(selectedTime.value.day - 1, currentDays.length - 1)
  const hourIndex = selectedTime.value.hour
  const minuteIndex = selectedTime.value.minute
  
  timePickerIndex.value = [
    yearIndex >= 0 ? yearIndex : 5,
    monthIndex,
    dayIndex,
    hourIndex,
    minuteIndex
  ]
}

// 时间选择器列变化（当选择年月时，需要更新日期列表）
const onTimePickerColumnChange = (e) => {
  const column = e.detail.column
  const row = e.detail.value
  
  // 如果改变的是年份或月份，需要更新日期列表
  if (column === 0) {
    // 年份改变
    selectedTime.value.year = years[row]
  } else if (column === 1) {
    // 月份改变
    selectedTime.value.month = months[row]
  }
  
  // 更新日期索引，确保不超出范围
  const currentDays = getDays(selectedTime.value.year, selectedTime.value.month)
  if (timePickerIndex.value[2] >= currentDays.length) {
    timePickerIndex.value[2] = currentDays.length - 1
  }
}

// 时间选择器变化
const onTimePickerChange = (e) => {
  const values = e.detail.value
  timePickerIndex.value = values
  
  // 更新选择的时间
  const yearList = timePickerRange.value[0]
  const monthList = timePickerRange.value[1]
  const dayList = timePickerRange.value[2]
  const hourList = timePickerRange.value[3]
  const minuteList = timePickerRange.value[4]
  
  selectedTime.value.year = yearList[values[0]].value
  selectedTime.value.month = monthList[values[1]].value
  
  // 处理日期索引
  const newDays = getDays(selectedTime.value.year, selectedTime.value.month)
  let dayIndex = values[2]
  if (dayIndex >= newDays.length) {
    dayIndex = newDays.length - 1
  }
  
  selectedTime.value.day = dayList[dayIndex].value
  selectedTime.value.hour = hourList[values[3]].value
  selectedTime.value.minute = minuteList[values[4]].value
  
  // 生成日期时间，保存为时间戳（毫秒）
  const date = new Date(
    selectedTime.value.year,
    selectedTime.value.month - 1,
    selectedTime.value.day,
    selectedTime.value.hour,
    selectedTime.value.minute
  )
  formData.value.startTime = date.getTime()
}

// 选择地点
const selectLocation = () => {
  uni.chooseLocation({
    success: (res) => {
      formData.value.location = res.address || res.name
      formData.value.longitude = res.longitude
      formData.value.latitude = res.latitude
    },
    fail: () => {
      uni.showToast({
        title: '定位失败',
        icon: 'none'
      })
    }
  })
}

// 打开指定用户选择弹框
const openDesignatedUsersModal = async () => {
  // 初始化选中用户为当前已选中的用户
  selectedUsers.value = [...formData.value.designatedUsers]
  // 加载关注列表
  await loadFollowList()
  showDesignatedUsersModal.value = true
}

// 关闭指定用户选择弹框
const closeDesignatedUsersModal = () => {
  showDesignatedUsersModal.value = false
}

// 加载关注列表
const loadFollowList = async () => {
  try {
    const FollowApi = (await import('@/sheep/api/member/follow')).default
    const res = await FollowApi.getFollowList()
    
    if (res && res.code === 0 && res.data) {
      followList.value = res.data || []
    } else {
      followList.value = []
    }
  } catch (error) {
    console.error('加载关注列表失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
    followList.value = []
  }
}

// 切换用户选择
const toggleUserSelect = (user) => {
  const userId = user.id
  const index = selectedUsers.value.indexOf(userId)
  if (index > -1) {
    // 已选中，取消选择
    selectedUsers.value.splice(index, 1)
  } else {
    // 未选中，添加选择
    selectedUsers.value.push(userId)
  }
}

// 检查用户是否被选中
const isUserSelected = (userId) => {
  return selectedUsers.value.includes(userId)
}

// 确认选择指定用户
const confirmDesignatedUsers = () => {
  formData.value.designatedUsers = [...selectedUsers.value]
  closeDesignatedUsersModal()
}

// 添加图片
const addImage = () => {
  const remain = 9 - formData.value.images.length
  if (remain <= 0) {
    uni.showToast({ title: '最多选择9张图片', icon: 'none' })
    return
  }

  uni.chooseImage({
    count: remain,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      try {
        const tasks = res.tempFilePaths.map(async (path) => {
          const result = await FileApi.uploadFile(path, 'buddy')
          return result?.data || null
        })
        const uploaded = (await Promise.all(tasks)).filter(Boolean)
        formData.value.images = [...formData.value.images, ...uploaded]
      } catch (e) {
        console.error('上传图片失败:', e)
        uni.showToast({
          title: '上传失败，请重试',
          icon: 'none'
        })
      }
    }
  })
}

// 删除图片
const removeImage = (index) => {
  formData.value.images.splice(index, 1)
}

// 发布
const handlePublish = async () => {
  if (!canPublish.value) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    })
    return
  }

  // 检查登录状态
  const token = uni.getStorageSync('token')
  const isLogin = userStore?.isLogin || !!token

  if (!isLogin) {
    uni.showToast({ title: '请先登录', icon: 'none' })
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/index/login'
      })
    }, 1500)
    return
  }

  uni.showLoading({ title: '发布中...' })
  try {
    // 性别限制转换：all -> 0, male -> 1, female -> 2
    const genderMap = {
      'all': 0,
      'male': 1,
      'female': 2
    }
    const genderLimit = genderMap[formData.value.gender] ?? 0
    
    // 支付方式转换：wallet -> WALLET, alipay -> ALIPAY, wechat -> WECHAT
    const paymentMethodMap = {
      'wallet': 'WALLET',
      'alipay': 'ALIPAY',
      'wechat': 'WECHAT'
    }
    const paymentMethod = paymentMethodMap[formData.value.paymentMethod] || 'WECHAT'
    
    // 时长从小时转换为分钟
    const durationMinutes = Math.round((parseFloat(formData.value.duration) || 0) * 60)
    
    // 计算支付金额：单价 * 参与人数
    const unitPrice = parseFloat(formData.value.price) || 0
    const participantCount = parseInt(formData.value.participants) || 1
    const paymentAmount = unitPrice * participantCount
    
    // 构建请求参数
    const requestData = {
      title: formData.value.title,
      buddyTypeId: formData.value.typeId,
      genderLimit: genderLimit,
      duration: durationMinutes,
      location: formData.value.location || null,
      longitude: formData.value.longitude || null,
      latitude: formData.value.latitude || null,
      images: formData.value.images || [],
      unitPrice: unitPrice,
      description: formData.value.content || '',
      startTime: formatStartTime(formData.value.startTime),
      participantCount: participantCount,
      specifiedUserIds: formData.value.designatedUsers || [],
      needConfirm: formData.value.needOnsiteConfirm,
      paymentMethod: paymentMethod,
      paymentAmount: paymentAmount
    }
    
    // 调用发布搭子API
    const res = await BuddyApi.createBuddyOrder(requestData)
    
    uni.hideLoading()
    
    if (res && res.code === 0) {
      const order = res.data
      
      // 根据支付方式处理
      if (paymentMethod === 'WALLET') {
        // 钱包支付：已支付成功，直接跳转
        if (order.payStatus) {
          uni.showToast({
            title: '支付成功',
            icon: 'success'
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: '支付失败，请重试',
            icon: 'none'
          })
        }
      } else if (paymentMethod === 'WECHAT' || paymentMethod === 'ALIPAY') {
        // 微信/支付宝支付：调起支付
        if (order.payOrderId && order.payChannelCode) {
          await handleThirdPartyPayment(order.payOrderId, order.payChannelCode, order.id)
        } else {
          uni.showToast({
            title: '创建支付订单失败',
            icon: 'none'
          })
        }
      } else {
        // 其他情况，直接返回
        uni.showToast({
          title: '发布成功',
          icon: 'success'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }
    } else {
      uni.showToast({
        title: res?.msg || '发布失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('发布失败:', error)
    uni.showToast({
      title: error?.msg || '发布失败，请重试',
      icon: 'none'
    })
  }
}

// 处理第三方支付（微信/支付宝）
const handleThirdPartyPayment = async (payOrderId, channelCode, orderId) => {
  try {
    uni.showLoading({ title: '调起支付中...' })
    
    // 准备传给后端的参数
    const submitParams = {
      id: payOrderId,
      channelCode: channelCode,
      returnUrl: '' // uni-app 中不需要 returnUrl
    }
    
    // 打印传给后端的参数
    console.log('调用 /app-api/pay/order/submit 接口，传给后端的参数:', JSON.stringify(submitParams, null, 2))
    console.log('参数详情:', {
      payOrderId: payOrderId,
      channelCode: channelCode,
      returnUrl: submitParams.returnUrl
    })
    
    // 调用支付接口获取支付参数
    const payRes = await PayOrderApi.submitOrder(submitParams)
    
    uni.hideLoading()
    
    if (!payRes || payRes.code !== 0) {
      uni.showToast({
        title: payRes?.msg || '获取支付参数失败',
        icon: 'none'
      })
      return
    }
    
    const payParams = payRes.data
    
    // 调试：打印支付参数
    console.log('支付参数:', payParams)
    console.log('支付渠道:', channelCode)
    
    if (channelCode === 'wx_app') {
      // 微信支付
      uni.requestPayment({
        provider: 'wxpay',
        timeStamp: payParams.timeStamp,
        nonceStr: payParams.nonceStr,
        package: payParams.package,
        signType: payParams.signType,
        paySign: payParams.paySign,
        success: () => {
          uni.showToast({
            title: '支付成功',
            icon: 'success'
          })
          // 轮询查询支付状态
          checkPaymentStatus(payOrderId, orderId)
        },
        fail: (err) => {
          console.error('微信支付失败:', err)
          if (err.errMsg && err.errMsg.includes('cancel')) {
            uni.showToast({
              title: '支付已取消',
              icon: 'none'
            })
          } else {
            uni.showToast({
              title: '支付失败',
              icon: 'none'
            })
          }
        }
      })
    } else if (channelCode === 'alipay_app') {
      // 支付宝APP支付
      // 根据后端返回的字段获取订单字符串
      const orderString = payParams.displayContent || payParams.orderStr || payParams.orderInfo
      
      if (!orderString) {
        console.error('支付宝支付参数错误，未找到订单字符串:', payParams)
        uni.showToast({
          title: '支付参数错误',
          icon: 'none'
        })
        return
      }
      
      // #ifdef APP-PLUS
      // uni-app 环境（推荐）
      uni.requestPayment({
        provider: 'alipay',
        orderInfo: orderString, // 订单字符串，直接使用后端返回的 displayContent
        success: (res) => {
          console.log('支付成功', res)
          uni.showToast({
            title: '支付成功',
            icon: 'success'
          })
          // 轮询查询支付状态
          checkPaymentStatus(payOrderId, orderId)
        },
        fail: (err) => {
          console.error('支付失败', err)
          
          // 处理不同的错误码
          if (err.errMsg && (err.errMsg.includes('cancel') || err.errMsg.includes('62001'))) {
            uni.showToast({
              title: '支付已取消',
              icon: 'none'
            })
          } else if (err.errMsg && err.errMsg.includes('62009')) {
            // 62009 未知错误，尝试使用 plus.payment
            console.error('支付宝支付错误码 62009，尝试使用 plus.payment')
            
            // 尝试使用 plus.payment（App 端原生支付 API）
            if (typeof plus !== 'undefined' && plus.payment) {
              plus.payment.getChannels((channels) => {
                const alipayChannel = channels.find(ch => ch.id === 'alipay')
                if (alipayChannel) {
                  console.log('使用 plus.payment 调起支付宝支付')
                  plus.payment.request(alipayChannel, orderString, (result) => {
                    console.log('plus.payment 支付宝支付成功:', result)
                    uni.showToast({
                      title: '支付成功',
                      icon: 'success'
                    })
                    // 轮询查询支付状态
                    checkPaymentStatus(payOrderId, orderId)
                  }, (error) => {
                    console.error('plus.payment 支付宝支付失败:', error)
                    
                    // 提供详细的错误提示和解决方案
                    uni.showModal({
                      title: '支付宝支付失败',
                      content: '错误码：62009（未知错误）\n\n可能原因：\n1. 支付宝客户端版本过旧（需最新版）\n2. App 支付配置需要重新编译打包\n3. 后端支付签名配置问题\n4. 支付宝开放平台配置问题\n\n建议操作：\n1. 更新支付宝客户端到最新版\n2. 重新编译打包 App（确保 manifest.json 配置生效）\n3. 检查后端支付配置（签名类型、证书等）\n4. 如仍失败，请使用微信支付或余额支付',
                      showCancel: true,
                      cancelText: '取消',
                      confirmText: '知道了'
                    })
                  })
                } else {
                  console.error('未找到支付宝支付渠道')
                  uni.showToast({
                    title: '支付失败，请确保已安装最新版支付宝客户端',
                    icon: 'none',
                    duration: 3000
                  })
                }
              }, (error) => {
                console.error('获取支付渠道失败:', error)
                uni.showToast({
                  title: '支付失败，请确保已安装最新版支付宝客户端',
                  icon: 'none',
                  duration: 3000
                })
              })
            } else {
              uni.showToast({
                title: err.errMsg || '支付失败，请重试',
                icon: 'none',
                duration: 2000
              })
            }
          } else {
            uni.showToast({
              title: err.errMsg || '支付失败，请重试',
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
      // #endif
      
      // #ifndef APP-PLUS
      uni.showToast({
        title: '支付宝支付仅支持 App 端',
        icon: 'none'
      })
      // #endif
    } else {
      uni.showToast({
        title: '不支持的支付方式',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('调起支付失败:', error)
    uni.showToast({
      title: '调起支付失败',
      icon: 'none'
    })
  }
}

// 轮询查询支付状态
const checkPaymentStatus = (payOrderId, orderId) => {
  let pollCount = 0
  const maxPollCount = 15 // 最多轮询15次（30秒）
  
  const timer = setInterval(async () => {
    pollCount++
    
    try {
      // 查询支付订单状态
      const res = await PayOrderApi.getOrder(payOrderId, true)
      
      if (res && res.code === 0 && res.data) {
        const payOrder = res.data
        
        // 如果支付成功
        if (payOrder.status === 20) { // 20 表示已支付
          clearInterval(timer)
          uni.showToast({
            title: '支付成功',
            icon: 'success'
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
          return
        }
      }
      
      // 如果超过最大轮询次数，停止轮询
      if (pollCount >= maxPollCount) {
        clearInterval(timer)
        // 可以选择跳转到订单详情页，让用户手动刷新
        uni.showToast({
          title: '支付处理中，请稍后查看订单',
          icon: 'none',
          duration: 2000
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 2000)
      }
    } catch (error) {
      console.error('查询支付状态失败:', error)
      // 如果查询失败，继续轮询，直到达到最大次数
      if (pollCount >= maxPollCount) {
        clearInterval(timer)
        uni.showToast({
          title: '支付处理中，请稍后查看订单',
          icon: 'none',
          duration: 2000
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 2000)
      }
    }
  }, 2000) // 每2秒查询一次
}

// 获取用户余额
const getUserBalance = async () => {
  try {
    const res = await UserApi.getUserInfo()
    if (res && res.code === 0 && res.data) {
      userBalance.value = res.data.balance || 0
    }
  } catch (error) {
    console.error('获取用户余额失败:', error)
    userBalance.value = 0
  }
}

onMounted(() => {
  getBuddyTypeList()
  // 初始化是否需要现场确认的索引
  needOnsiteConfirmIndex.value = formData.value.needOnsiteConfirm ? 0 : 1
  // 获取用户余额
  getUserBalance()
  // 初始化时间选择器
  initTimePicker()
})
</script>

<style lang="scss" scoped>
.publish-buddy-page {
  min-height: 100vh;
  background: #f6f6f6;
  display: flex;
  flex-direction: column;
}

.header {
  position: relative;
  width: 100%;
  height: 480rpx;
  z-index: 0;
}

.header-image {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.header-bar {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  padding: 20rpx 24rpx;
  padding-top: calc(80rpx + env(safe-area-inset-top));
  padding-top: calc(20rpx + constant(safe-area-inset-top));
  display: flex;
  align-items: center;
  gap: 16rpx;
  z-index: 20;
}

.back-btn {
  width: 80rpx;
  height: 80rpx;
}

.page-title-image {
  width: 160rpx;
  height: 50rpx;
}

.form-content {
  flex: 1;
  margin-top: -290rpx;
  padding-bottom: 200rpx;
  height: calc(100vh - 480rpx);
  box-sizing: border-box;
}

.form-card {
  background: #fff;
  margin: 0 17rpx 24rpx;
  border-radius: 24rpx;
  padding: 24rpx;
  position: relative;
  z-index: 10;
}

.payment-card {
  background: #fff;
  margin: 0 17rpx 24rpx;
  border-radius: 24rpx;
  padding: 24rpx;
  position: relative;
  z-index: 1;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
}

.form-item-full {
  flex-direction: column;
  align-items: flex-start;
  width: 100%;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  width: 200rpx;
  flex-shrink: 0;
  font-weight: bold;
  white-space: nowrap;
}

.form-value {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  text-align: right;
}

.form-value-text {
  font-size: 28rpx;
  color: #333;
  margin-right: 12rpx;
  flex: 1;
  text-align: right;

  &.placeholder {
    color: #999;
  }
}

.form-value-inner {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  text-align: right;
  width: 100%;
}

/* 使用深度选择器强制应用picker内部样式 */
:deep(picker) {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

:deep(picker .form-value) {
  width: 100% !important;
  display: flex !important;
  align-items: center !important;
  justify-content: flex-end !important;
  flex: 1 !important;
}

:deep(picker .form-value-text) {
  text-align: right !important;
  flex: 1 !important;
  margin-right: 12rpx !important;
}

/* 确保时间选择器弹框在支付方式白框之上 */
:deep(.uni-datetime-picker-mask) {
  z-index: 2001 !important;
}

:deep(.uni-datetime-picker-popup) {
  z-index: 2002 !important;
}

:deep(.uni-date-mask) {
  z-index: 2001 !important;
}

:deep(.uni-date-single--x),
:deep(.uni-date-range--x) {
  z-index: 2002 !important;
}

.form-input {
  flex: 1;
  text-align: right;
  font-size: 28rpx;
  color: #333;
}

.form-unit {
  font-size: 28rpx;
  color: #333;
  margin-left: 12rpx;
}

.form-textarea {
  width: 100%;
  min-height: 300rpx;
  background: #f7f7f9;
  border-radius: 16rpx;
  padding: 20rpx;
  box-sizing: border-box;
  font-size: 28rpx;
  color: #333;
  margin-top: 20rpx;
  margin-bottom: 0;
  padding-bottom: 0;
}

.upload-card {
  width: calc((100% - 24rpx) / 3);
  height: 200rpx;
  background: #f7f7f9;
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 0;
  margin-bottom: 12rpx;
  flex-shrink: 0;
  box-sizing: border-box;
}

.camera-icon {
  width: 80rpx;
  height: 80rpx;
  opacity: 0.9;
}

.upload-text {
  margin-top: 12rpx;
  font-size: 24rpx;
  color: #666;
}

.upload-tips {
  display: block;
  margin-top: 12rpx;
  font-size: 24rpx;
  color: #8a8f98;
}

.gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-top: 12rpx;
  width: 100%;
}

.gallery-item {
  width: calc((100% - 24rpx) / 3);
  height: 200rpx;
  position: relative;
  border-radius: 16rpx;
  overflow: hidden;
  flex-shrink: 0;
  box-sizing: border-box;
}

.gallery-image {
  width: 100%;
  height: 100%;
  display: block;
}

.gallery-delete {
  position: absolute;
  top: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.75);
  padding: 5rpx 8rpx;
  border-bottom-left-radius: 12rpx;
  z-index: 999;
}

.delete-icon {
  width: 28rpx;
  height: 28rpx;
}

.upload-card-small {
  width: calc((100% - 24rpx) / 3);
  height: 200rpx;
  background: #f7f7f9;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.camera-icon-small {
  width: 60rpx;
  height: 60rpx;
  opacity: 0.9;
}

.payment-title {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 24rpx;
}

.payment-item {
  display: block;
  
  .pay-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    
    .pay-item-left {
      display: flex;
      align-items: center;
      flex: 1;
      
      .pay-icon-wrapper {
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 24rpx;
        flex-shrink: 0;
        
        .pay-icon {
          width: 60rpx;
          height: 60rpx;
          border-radius: 50%;
        }
      }
      
      .pay-item-info {
        display: flex;
        flex-direction: column;
        flex: 1;
        
        .pay-method-title {
          font-size: 28rpx;
          font-weight: 500;
          color: #333;
          margin-bottom: 8rpx;
        }
        
        .pay-method-desc {
          font-size: 22rpx;
          color: #999;
          line-height: 1.4;
        }
      }
    }
    
    .pay-item-right {
      display: flex;
      align-items: center;
      flex-shrink: 0;
    }
  }
}

.radio-circle {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  border: 2rpx solid #ddd;
  position: relative;

  &.checked {
    border-color: #74A7FF;
    background: #74A7FF;

    &::after {
      content: '';
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 20rpx;
      height: 20rpx;
      border-radius: 50%;
      background: #fff;
    }
  }
}

.publish-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 24rpx;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  background: #fff;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.publish-btn {
  width: 100%;
  height: 96rpx;
  line-height: 96rpx;
  border-radius: 48rpx;
  color: #fff;
  font-size: 32rpx;
  border: none;
  background: linear-gradient(90deg, #B276FF 0%, #74A7FF 100%);
}

.publish-btn[disabled] {
  opacity: 0.5;
  color: #fff;
}


// 指定用户选择弹框
.designated-users-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 2000;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}

.designated-users-content {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  width: 100%;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.designated-users-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .designated-users-cancel {
    font-size: 28rpx;
    color: #999;
  }
  
  .designated-users-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
  }
  
  .designated-users-confirm {
    font-size: 28rpx;
    color: #2977FF;
  }
}

.designated-users-list {
  flex: 1;
  max-height: calc(80vh - 100rpx);
  overflow-y: auto;
}

.designated-user-item {
  display: flex;
  align-items: center;
  padding: 25rpx 34rpx;
  position: relative;
  
  &:not(:last-child)::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 34rpx;
    right: 34rpx;
    height: 1px;
    background: #f1f2f5;
  }
}

.designated-user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 24rpx;
  background: #f2f2f2;
}

.designated-user-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-width: 0;
}

.designated-user-nickname {
  font-size: 28rpx;
  font-weight: bold;
  color: #26272a;
  margin-bottom: 10rpx;
  word-break: break-all;
  white-space: normal;
}

.designated-user-id {
  color: #676767;
  font-size: 24rpx;
  font-weight: 400;
}

.designated-user-checkbox {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 20rpx;
}

.checkbox-icon {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  border: 2rpx solid #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  
  &.checked {
    background: #2977FF;
    border-color: #2977FF;
    
    .checkbox-check {
      color: #fff;
      font-size: 24rpx;
      font-weight: bold;
    }
  }
}

.empty-tip {
  text-align: center;
  padding: 80rpx 0;
  color: #999;
  font-size: 28rpx;
}
</style>

